Page({
  data: {
    categories:[],
    subCategories:[],
    request_json:{
          "category_id":0
    },
  },
  onLoad() {
      this.getCategory();
      console.log(this.data);
      // this.getCategory(this.data.categories[0].id);
    },

    category_tap(e){
       my.navigateTo({
      url: `/pages/main/goodsList/goodsList?category_id=${e.currentTarget.id}`, // 需要跳转的 tabBar 页面的路径（需在 app.json 的 tabBar 字段定义的页面），路径后不能带参数
    });
    },
    
    //click tab
    clickCategory(e){
      this.getCategory(e.currentTarget.id);
      this.setActive(e.target.dataset.index);      
      },

      //设置选中效果
      setActive(index){
           if(this.data.categories != '')
          {
            var cate = this.data.categories;
            // var show ='';
            console.log(this.data.categories);
            if(this.data.categories == null)
              return;
            for(var i=0;i<this.data.categories.length;i++){
              if(i==index){
                //  this.data.categories[i].show = 'li active';
                cate[i].show = 'li active';
              }
              else
                cate[i].show = 'li';
                this.setData({
                  categories : cate
                })
            }
          }
      },
              
  //获取分类 x不填获取根目录
  getCategory(x){
      var app = getApp()
      var url = app.globadData.apiUrlHeader+'get-categories'
      if(x != undefined){
        var jj = {"category_id":x,"access_token":app.globadData.access_token};
        this.setData({
          request_json : jj
          // "access_token":app.globadData.access_token
        })
      }else{//获取主分类
       var jj = {"category_id":"0","access_token":app.globadData.access_token};
        this.setData({
          request_json : jj
          // "access_token":app.globadData.access_token          
        })
      }
      console.log(this.data.request_json);
      my.httpRequest({
      url: url, // 目标服务器 url
      method:'Post',
      headers:{'Content-Type':'Application/json'},
      data:JSON.stringify(this.data.request_json),
        dataType:'json',
        success: (res) => {
          console.log(res);
          if(x != undefined){
          this.setData({
            subCategories : res.data.data
          })
          // this.setActive(x);
          }else{//设置主分类
            this.setData({
            categories : res.data.data
            })
            this.setActive(0);
            // console.log(res.data.data.length);
            if(res.data.data !=null && res.data.data.length>0)
            this.getCategory(res.data.data[0].id);
          }
        // }
      },
    });

  }
});
